import { prisma } from '../lib/database.js'
import bcrypt from 'bcryptjs'

async function main() {
  console.log('🌱 Starting database seeding...')

  try {
    // 清理现有数据（开发环境）
    console.log('🧹 Cleaning existing data...')
    await prisma.auditLog.deleteMany()
    await prisma.download.deleteMany()
    await prisma.securityScan.deleteMany()
    await prisma.pluginVersion.deleteMany()
    await prisma.review.deleteMany()
    await prisma.pluginTag.deleteMany()
    await prisma.plugin.deleteMany()
    await prisma.tag.deleteMany()
    await prisma.category.deleteMany()
    await prisma.apiKey.deleteMany()
    await prisma.systemConfig.deleteMany()
    await prisma.developer.deleteMany()

    // 创建开发者用户
    console.log('👤 Creating developers...')
    const passwordHash = await bcrypt.hash('password123', 12)
    
    const developer1 = await prisma.developer.create({
      data: {
        username: 'john_dev',
        email: 'john@example.com',
        passwordHash,
        displayName: 'John Developer',
        bio: 'Full-stack developer passionate about plugins',
        verified: true,
        emailVerified: true,
        status: 'active'
      }
    })

    const developer2 = await prisma.developer.create({
      data: {
        username: 'jane_dev',
        email: 'jane@example.com',
        passwordHash,
        displayName: 'Jane Smith',
        bio: 'Frontend specialist and UI/UX designer',
        verified: true,
        emailVerified: true,
        status: 'active'
      }
    })

    // 创建管理员用户
    await prisma.developer.create({
      data: {
        username: 'admin',
        email: 'admin@plugin-cloud.com',
        passwordHash,
        displayName: 'System Administrator',
        bio: 'Platform administrator',
        role: 'admin',
        verified: true,
        emailVerified: true,
        status: 'active'
      }
    })

    // 创建分类
    console.log('📂 Creating categories...')
    await Promise.all([
      prisma.category.create({
        data: {
          name: 'productivity',
          displayName: 'Productivity',
          description: 'Tools to boost your productivity',
          icon: 'productivity',
          color: '#3B82F6',
          sortOrder: 1
        }
      }),
      prisma.category.create({
        data: {
          name: 'development',
          displayName: 'Development',
          description: 'Development tools and utilities',
          icon: 'code',
          color: '#10B981',
          sortOrder: 2
        }
      }),
      prisma.category.create({
        data: {
          name: 'ui-ux',
          displayName: 'UI/UX',
          description: 'User interface and experience tools',
          icon: 'design',
          color: '#F59E0B',
          sortOrder: 3
        }
      }),
      prisma.category.create({
        data: {
          name: 'automation',
          displayName: 'Automation',
          description: 'Workflow automation tools',
          icon: 'automation',
          color: '#8B5CF6',
          sortOrder: 4
        }
      })
    ])

    // 创建标签
    console.log('🏷️ Creating tags...')
    await Promise.all([
      prisma.tag.create({
        data: {
          name: 'popular',
          displayName: 'Popular',
          description: 'Popular plugins',
          color: '#EF4444'
        }
      }),
      prisma.tag.create({
        data: {
          name: 'featured',
          displayName: 'Featured',
          description: 'Featured plugins',
          color: '#F59E0B'
        }
      }),
      prisma.tag.create({
        data: {
          name: 'new',
          displayName: 'New',
          description: 'Recently added plugins',
          color: '#10B981'
        }
      }),
      prisma.tag.create({
        data: {
          name: 'recommended',
          displayName: 'Recommended',
          description: 'Recommended by the community',
          color: '#3B82F6'
        }
      })
    ])

    // 创建示例插件
    console.log('🔌 Creating sample plugins...')
    const plugin1 = await prisma.plugin.create({
      data: {
        name: '@bai-hu-plugin/task-manager',
        displayName: 'Task Manager',
        description: 'A powerful task management plugin for organizing your work',
        category: 'productivity',
        developerId: developer1.id,
        repositoryUrl: 'https://github.com/john_dev/task-manager',
        homepageUrl: 'https://task-manager.example.com',
        license: 'MIT',
        keywords: ['task', 'management', 'productivity', 'todo'],
        tags: ['popular', 'featured'],
        status: 'approved',
        featured: true,
        verified: true,
        totalDownloads: 1250,
        ratingAverage: 4.8,
        ratingCount: 45,
        lastVersion: '1.2.0'
      }
    })

    const plugin2 = await prisma.plugin.create({
      data: {
        name: '@bai-hu-plugin/code-formatter',
        displayName: 'Code Formatter',
        description: 'Automatically format your code with multiple language support',
        category: 'development',
        developerId: developer2.id,
        repositoryUrl: 'https://github.com/jane_dev/code-formatter',
        license: 'Apache-2.0',
        keywords: ['code', 'formatter', 'development', 'prettier'],
        tags: ['popular', 'recommended'],
        status: 'approved',
        featured: false,
        verified: true,
        totalDownloads: 890,
        ratingAverage: 4.6,
        ratingCount: 32,
        lastVersion: '2.1.1'
      }
    })

    await prisma.plugin.create({
      data: {
        name: '@bai-hu-plugin/ui-components',
        displayName: 'UI Components Library',
        description: 'A collection of beautiful and reusable UI components',
        category: 'ui-ux',
        developerId: developer2.id,
        repositoryUrl: 'https://github.com/jane_dev/ui-components',
        license: 'MIT',
        keywords: ['ui', 'components', 'design', 'react'],
        tags: ['new', 'featured'],
        status: 'pending',
        featured: false,
        verified: false,
        totalDownloads: 156,
        ratingAverage: 4.9,
        ratingCount: 8,
        lastVersion: '0.9.0'
      }
    })

    // 创建插件版本
    console.log('📦 Creating plugin versions...')
    await prisma.pluginVersion.create({
      data: {
        pluginId: plugin1.id,
        version: '1.2.0',
        changelog: 'Added new task filtering options and improved performance',
        filePath: '/uploads/task-manager-1.2.0.zip',
        fileSize: 2048576,
        fileHash: 'sha256:abc123def456...',
        manifest: {
          name: '@bai-hu-plugin/task-manager',
          version: '1.2.0',
          engines: { host: '>=0.1.0' },
          permissions: ['storage:read', 'storage:write']
        },
        engines: { host: '>=0.1.0' },
        permissions: ['storage:read', 'storage:write'],
        status: 'approved',
        downloadCount: 1250,
        securityScanStatus: 'passed',
        publishedAt: new Date()
      }
    })

    await prisma.pluginVersion.create({
      data: {
        pluginId: plugin2.id,
        version: '2.1.1',
        changelog: 'Fixed formatting issues with TypeScript files',
        filePath: '/uploads/code-formatter-2.1.1.zip',
        fileSize: 1536000,
        fileHash: 'sha256:def456ghi789...',
        manifest: {
          name: '@bai-hu-plugin/code-formatter',
          version: '2.1.1',
          engines: { host: '>=0.1.0' },
          permissions: ['fs:read', 'fs:write']
        },
        engines: { host: '>=0.1.0' },
        permissions: ['fs:read', 'fs:write'],
        status: 'approved',
        downloadCount: 890,
        securityScanStatus: 'passed',
        publishedAt: new Date()
      }
    })

    // 创建系统配置
    console.log('⚙️ Creating system configs...')
    await prisma.systemConfig.createMany({
      data: [
        {
          key: 'site.name',
          value: 'Bai-hu Plugin Cloud',
          description: 'Site name',
          category: 'general',
          isPublic: true
        },
        {
          key: 'site.description',
          value: 'The official plugin marketplace for Bai-hu',
          description: 'Site description',
          category: 'general',
          isPublic: true
        },
        {
          key: 'upload.maxFileSize',
          value: 104857600,
          description: 'Maximum file size for plugin uploads (bytes)',
          category: 'upload',
          isPublic: false
        },
        {
          key: 'security.requireSignature',
          value: false,
          description: 'Require plugin signature verification',
          category: 'security',
          isPublic: false
        }
      ]
    })

    console.log('✅ Database seeding completed successfully!')
    console.log(`📊 Created:`)
    console.log(`   - ${await prisma.developer.count()} developers`)
    console.log(`   - ${await prisma.category.count()} categories`)
    console.log(`   - ${await prisma.tag.count()} tags`)
    console.log(`   - ${await prisma.plugin.count()} plugins`)
    console.log(`   - ${await prisma.pluginVersion.count()} plugin versions`)
    console.log(`   - ${await prisma.systemConfig.count()} system configs`)

  } catch (error) {
    console.error('❌ Error during seeding:', error)
    throw error
  }
}

main()
  .catch((e) => {
    console.error(e)
    process.exit(1)
  })
  .finally(async () => {
    await prisma.$disconnect()
  })
